package com.nhim.cms.web;

import java.io.File;

import org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.ContentDisposition;
import org.apache.wicket.util.resource.FileResourceStream;

import com.nhim.core.AppSettings;
import com.nhim.core.io.PathHelper;

public class Dispatcher extends BasePage {
	
	private static final long serialVersionUID = 1L;

	public Dispatcher(final PageParameters parameters) {
		if (parameters.getIndexedCount() > 0) {
			
			String path = processParameters(parameters);
			if (!"".equals(path)) {
				String physicalFilePath = PathHelper.combine(new String[] {AppSettings.getInstance().getTemplatesPath(), path });
				if ((new File(physicalFilePath)).exists()) {
					FileResourceStream stream = new FileResourceStream(new File(physicalFilePath));
					getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(stream).setFileName(path).setContentDisposition(ContentDisposition.ATTACHMENT));
					return;
				}
			} else
				path = findHomePagePath();
		}
		buildPage();
	}

	private String processParameters(PageParameters parameters) {
		StringBuilder sb = new StringBuilder();
		if (parameters.getIndexedCount() > 0) {
			for (int i = 0; i < parameters.getIndexedCount(); i++) {
				sb.append("/" + parameters.get(i) );
			}
		}
		return sb.toString();

	}

	private String findHomePagePath() {
		return "";
	}

}
